package com.czi.webrtctemp

import WebRTCUI
import android.Manifest.permission.CAMERA
import android.Manifest.permission.INTERNET
import android.Manifest.permission.RECORD_AUDIO
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.*

import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.webrtc.*

class MainActivity : ComponentActivity() {
    // 日志标签
    companion object {
        private const val TAG = "视频通话界面"
        private const val REQUEST_CODE_PERMISSIONS = 1001
        private const val NOTIFICATION_PERMISSION_CODE = 1002
    }

    // WebRTC核心组件
    private lateinit var eglBase: EglBase
    private lateinit var webRTCClient: WebRTCClient
    private var localSurfaceView: SurfaceViewRenderer? = null
    private var remoteSurfaceView: SurfaceViewRenderer? = null

    // 权限配置
    private val requiredPermissions = arrayOf(CAMERA, RECORD_AUDIO, INTERNET)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "正在初始化主界面...")
        enableEdgeToEdge()

        if (!hasPermissions()) {
            Log.d(TAG, "检测到未授权，正在申请权限...")
            ActivityCompat.requestPermissions(
                this,
                requiredPermissions,
                REQUEST_CODE_PERMISSIONS
            )
        } else {
            Log.d(TAG, "权限已授予，准备初始化WebRTC")
            initializeWebRTC()
        }
    }

    private fun hasPermissions(): Boolean {
        return requiredPermissions.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_CODE_PERMISSIONS -> handlePermissionResult(grantResults)
//            NOTIFICATION_PERMISSION_CODE -> handleNotificationPermission()
        }
    }

    private fun handlePermissionResult(grantResults: IntArray) {
        val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
        if (allGranted) {
            initializeWebRTC()
        } else {
            showPermissionDeniedDialog()
        }
    }

    // 可选：添加权限拒绝后的处理对话框
    private fun showPermissionDeniedDialog() {
        AlertDialog.Builder(this)
            .setTitle("权限要求")
            .setMessage("需要摄像头和麦克风权限才能进行视频通话")
            .setPositiveButton("去设置") { _, _ ->
                startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.fromParts("package", packageName, null)
                })
            }
            .setNegativeButton("退出") { _, _ -> finish() }
            .setCancelable(false)
            .show()
    }

    private fun initializeWebRTC() {
        Log.d(TAG, "正在初始化WebRTC引擎...")
        eglBase = EglBase.create().also {
            Log.d(TAG, "EGL基础环境创建完成")
        }

        webRTCClient = WebRTCClient(
            context = this,
            eglBase = eglBase,
            signalingServer = "http://8.138.118.180:16686/rtc/webrtc/play"
        ).also {
            Log.d(TAG, "WebRTC客户端初始化完成")
        }

        // 初始化 SurfaceViewRenderer
        localSurfaceView = SurfaceViewRenderer(this).apply {
            init(eglBase.eglBaseContext, null)
            setZOrderMediaOverlay(true)
            setMirror(true)
            webRTCClient.initializeLocalStream(this)
        }

        remoteSurfaceView = SurfaceViewRenderer(this).apply {
            init(eglBase.eglBaseContext, null)
            setEnableHardwareScaler(true)
            setZOrderMediaOverlay(true)
            setMirror(false)
            setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT)
        }

        setContent {
            var connectionState by remember { mutableStateOf("连接已断开") }

            WebRTCUI(
                connectionState = connectionState,
                onStartConnection = {
                    connectionState = "正在连接..."
                    lifecycleScope.launch {
                        val success = startConnection()
                        connectionState = if (success) "已连接" else "连接失败"
                    }
                },
                onStopConnection = {
                    connectionState = "正在断开..."
                    lifecycleScope.launch {
                        val success = stopConnection()
                        connectionState = if (success) "连接已断开" else "断开失败"
                    }
                },
                localSurfaceView = localSurfaceView,
                remoteSurfaceView = remoteSurfaceView
            )
        }
    }

    override fun onDestroy() {
        Log.d(TAG, "正在销毁Activity，释放资源...")
        runCatching {
            localSurfaceView?.release()
            Log.d(TAG, "本地Surface已释放")
        }.onFailure { Log.e(TAG, "释放本地Surface失败", it) }

        runCatching {
            remoteSurfaceView?.release()
            Log.d(TAG, "远端Surface已释放")
        }.onFailure { Log.e(TAG, "释放远端Surface失败", it) }

        runCatching {
            webRTCClient.release()
            Log.d(TAG, "WebRTC客户端已释放")
        }.onFailure { Log.e(TAG, "释放WebRTC客户端失败", it) }

        runCatching {
            eglBase.release()
            Log.d(TAG, "EGL环境已释放")
        }.onFailure { Log.e(TAG, "释放EGL环境失败", it) }

        super.onDestroy()
        Log.d(TAG, "Activity销毁完成")
    }

    private suspend fun startConnection(): Boolean = withContext(Dispatchers.IO) {
        Log.d(TAG, "正在建立连接...")

        remoteSurfaceView?.let { surface ->
            webRTCClient.startCall(
                app = "live",
                stream = "sai",
                remoteSurface = surface
            ).fold(
                onSuccess = {
                    Log.d(TAG, "通话建立成功")
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@MainActivity, "通话建立成功", Toast.LENGTH_SHORT).show()
                    }
                    true
                },
                onFailure = { e ->
                    Log.e(TAG, "通话建立失败", e)
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@MainActivity, "通话建立失败", Toast.LENGTH_SHORT).show()
                    }
                    false
                }
            )
        } ?: run {
            Log.e(TAG, "远端Surface未就绪")
            false
        }
    }

    private suspend fun stopConnection(): Boolean = withContext(Dispatchers.IO) {
        Log.d(TAG, "正在断开连接...")
        runCatching {
            webRTCClient.release()
            Log.d(TAG, "连接已断开")
            withContext(Dispatchers.Main) {
                Toast.makeText(this@MainActivity, "已断开连接", Toast.LENGTH_SHORT).show()
            }
            true
        }.onFailure { e ->
            Log.e(TAG, "断开连接时出错", e)
            withContext(Dispatchers.Main) {
                Toast.makeText(this@MainActivity, "断开连接时出错", Toast.LENGTH_SHORT).show()
            }
            false
        }.getOrDefault(false)
    }
}
